package com.bbh.plugin.single.privilege.demo.framework;

import com.bbh.common.utils.rsa.RSAService;
import com.bbh.common.utils.rsa.RSAUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.security.KeyPair;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;

/**
 * Service - RSA安全
 *
 * @author BBH Team
 * @version 1.0
 */
@Component("rsaServiceImpl")
public class RSAServiceImpl implements RSAService {
    /**
     * "私钥"参数名称
     */
    private static final String PRIVATE_KEY_ATTRIBUTE_NAME = "privateKey";

    public RSAPublicKey generateKey() {
        //HttpServletRequest request = getRequest();
        // Assert.notNull(request);
        KeyPair keyPair = RSAUtils.generateKeyPair();
        RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
        RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
        Session session = getSession();
        session.setAttribute(PRIVATE_KEY_ATTRIBUTE_NAME, privateKey);
        return publicKey;
    }

    /**
     * 获取session
     *
     * @return
     */
    public Session getSession() {
        Session session = SecurityUtils.getSubject().getSession();
        return session;
    }

    public void removePrivateKey() {
        // HttpServletRequest request = getRequest();
        // Assert.notNull(request);
        Session session = getSession();
        session.removeAttribute(PRIVATE_KEY_ATTRIBUTE_NAME);
    }

    public String decryptParameter(String name) {
        HttpServletRequest request = getRequest();
        Assert.notNull(request);
        if (name != null) {
            Session session = getSession();
            RSAPrivateKey privateKey = (RSAPrivateKey) session.getAttribute(PRIVATE_KEY_ATTRIBUTE_NAME);
            String parameter = request.getParameter(name);
            if (privateKey != null && StringUtils.isNotEmpty(parameter)) {
                return RSAUtils.decrypt(privateKey, parameter);
            }
        }
        return null;
    }

    private HttpServletRequest getRequest() {
        HttpServletRequest req = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        return req;
    }

}